import sqlite3
from urllib.parse import urlparse

import numpy
import pandas as pd
from matplotlib import pyplot as plt

plt.rcParams['font.sans-serif'] = ['KaiTi']  # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题

# 谷歌浏览器历史记录的地址
# db_path = 'C:/Users/10331/AppData/Local/Google/Chrome/User Data/Default/History'
db_path = 'C:/Users/Microsoft/AppData/Local/Google/Chrome/User Data/Default/History'
conn = sqlite3.connect(db_path)

# 执行
cursor = conn.execute('select url from urls')
# 获取所有URL
urls = cursor.fetchall()

dict_ = {}
for url in urls:
    domain_name = urlparse(url[0]).netloc  # 获取域名
    if domain_name.count('.') == 2:
        domain_name = domain_name[domain_name.find('.') + 1:]
    count = dict_.get(domain_name)
    dict_[domain_name] = 1 if count is None else count + 1
if dict_.get('') is not None:
    dict_.pop('')  # 删除空的key

pf = pd.DataFrame({'count': list(dict_.values())}, index=dict_.keys()) \
         .sort_values(by=['count'], ascending=False)[:20]

list_explode = list(numpy.zeros(20))
# 设置次数最多的那个突出
list_explode[0] = 0.2

plt.figure(dpi=500, figsize=(10, 10), facecolor='#90EE90')
plt.title('Google历史记录访问前20的网站', size=30, color='m')
plt.pie(pf['count'], autopct='%1.1f%%', labels=pf.index, explode=list_explode)
# plt.legend(bbox_to_anchor=(1,0.66), loc=3, borderaxespad=0)
plt.show()
